<template>
	<view>
		<view class="history-tips" v-if="isShowHistoryMsgTips">加载历史消息。。。</view>

		<view class="container" @tap="togglePicker(0)">
			<!-- 1，消息主要内容 -->
			<view class="message" :style="{'height':scrollHeight}">
				<view style="height: 10px;"></view>
				<scroll-view ref="scrollViewRef" :upper-threshold="50" :scroll-top="scrollTop"
					:scroll-into-view="scrollViewId" scroll-y style="height: calc(100% - 20px);" show-scrollbar="true"
					:scroll-with-animation="scrollWithAnimation" @scroll="onScroll" @scrolltolower="onScrolltolower">
					<view v-for="(item,index) in chatList" :key="index" :id="'msg' + item.msgId">
						<!-- <view>{{'msg:' + index}}</view> -->
						<chat-msg-item @imgLoad="imgLoad" :chatItem="item" :chatItemIndex="index" @showImg="showImg"
							@showRedPkg="showRedPkg" @gotoUserSet="gotoUserSet" @handleAudio="handleAudio"
							@longpressItem="longpressItem">

							<!-- 时间处理器 -->
							<template v-slot:chatTime>
								<view>{{computeDate(item.time , index)}}</view>
							</template>

						</chat-msg-item>
					</view>
					<view id="bottom-anchor"></view>
				</scroll-view>
				<view style="height: 10px;"></view>
			</view>

			<!-- 2，输入框框主要内容 -->
			<view class="send" @tap.prevent.stop="" v-if="!isShowSend">
				<view class="send-row">
					<!--语音切换-->
					<image v-if="isEdit" @tap="toggleEdit(false)" src="../common/img/send/voice.svg" class="icon">
					</image>
					<image v-else @tap="toggleEdit(true)" src="../common/img/send/keyboard.svg" class="icon"></image>
					<!--语音切换-->
					<!-- <form @submit="submitInput">
				</form> -->
					<input v-if="isEdit" @focus="inputFocus" :focus="isFocus" :cursor-spacing="40"
						:adjust-position="isAdjustPosition" confirm-type="send" cursor-spacing="40"
						@confirm="sendMessage" @input="textareaBInput" v-model="content" class="input"
						placeholder="请文明发言..." />

					<view v-else @touchstart="micTouchStart" @touchmove="micTouchMove" @touchcancel="micTouchCancel"
						@touchend="micTouchEnd" class="input" style="text-align: center;">
						按住开吼
					</view>

					<!--表情-->
					<image @tap="togglePicker(200, 'emoji')" src="../common/img/send/emoji.svg" class="icon"></image>
					<!--发送-->
					<view @touchend.prevent="sendMessageByBtn" v-if="isShowSendBtn" class="btn">发送</view>
					<!--附件-->
					<image @tap="togglePicker(150, 'file')" v-else src="../common/img/send/add.svg" class="icon">
					</image>
				</view>

				<view class="send-new-msg" @click="gotoBottomByTips"
					:style="{'visibility':newMsgVisibility,'opacity':newMsgOpacity}">
					<text>有新消息</text>
				</view>

				<transition name="fade">
					<!-- 3，工具栏框 -->
					<view v-if="showFile" class="send-file" @tap.prevent.stop="">
						<view class="send-file-list">
							<view class="file-box">
								<view class="file-box-item" @tap="chooseIamgeFromAlbum(['album'])">
									<image src="../common/img/file/02.svg" class="icon"></image>
									<view class="text">相册</view>
								</view>
							</view>
							<view class="file-box">
								<view class="file-box-item" @tap="chooseIamgeFromCamera(['camera'])">
									<image src="../common/img/file/03.svg" mode="widthFix" class="icon"></image>
									<view class="text">拍摄</view>
								</view>
							</view>
							<view class="file-box">
								<view class="file-box-item" @tap="sendRedPkg">
									<image src="../common/img/file/04.svg" mode="widthFix" class="icon"></image>
									<view class="text">红包</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 4，表情库 -->
					<view v-if="showEmoji" class="emoji" @tap.prevent.stop="">
						<chat-send-emoji @clickEmoji="clickEmoji" :height="emojiHight"></chat-send-emoji>
					</view>
				</transition>
			</view>
			<view class="send" @tap.prevent.stop="" v-else>
				<view class="send-row">
					<image src="../common/img/send/voice.svg" class="icon"></image>
					<view class="input" style="text-align: center;">
						{{sendTitle}}
					</view>
					<!--表情-->
					<image src="../common/img/send/emoji.svg" class="icon"></image>
					<!--附件-->
					<image src="../common/img/send/add.svg" class="icon">
					</image>
				</view>
			</view>


			<!-- 5，长按弹框 -->
			<chat-con-tool :popButton="popButton" :showShade="showShade" :showPop="showPop" :popStyle="showHeightStyle"
				@pickerMenu="pickerMenu" @hidePop="closeShowTool"></chat-con-tool>

			<!-- 7，发送语音动画 -->
			<chat-voice-icon :isShow="isShowVoiceIcon" :titleText="voiceIconTitle"
				:voiceBgColor="voiceBgColor"></chat-voice-icon>

			<!-- 8，@框 -->
			<chat-at-animation @selectUser="selectUser" :share="isShowAtGroup" :groupUsers="groupUsers"
				@display="closeAtGroup"></chat-at-animation>
		</view>

		<!-- 红包信息 -->
		<chat-redpkg-animation @closeHbFun="closeHbFun" :showHbMsg="showHbMsg" :rbagmodelshow="isShowHb"
			@openHbFun="openHbFun" :openbrnanimation="openbrnanimation" :openrbagmodelshow="openrbagmodelshow"
			@gotoDetail="gotoDetail"></chat-redpkg-animation>
	</view>
</template>

<script>
	//1，引入公共组件
	import chatSendEmoji from '@/components/content/my-new-chat/child/chat-send-emoji.vue'
	import chatMsgItem from '@/components/content/my-new-chat/child/chat-msg-item.vue'
	import chatConTool from '@/components/content/my-new-chat/child/chat-con-tool.vue'
	import chatAdd from '@/components/content/my-new-chat/child/chat-add.vue'
	import chatVoiceIcon from '@/components/content/my-new-chat/child/chat-voice-icon/index.vue'
	import chatAtAnimation from '@/components/content/my-new-chat/child/chat-at-animation.vue'
	import chatRedpkgAnimation from '@/components/content/my-chat/common/chat-redpkg/redpkg-animation.vue'

	//2，时间工具处理
	import {
		handleTime,
		timeago
	} from '@/components/content/my-new-chat/utils/time.js'
	import {
		getNowTime
	} from '@/utils/time/time.js'

	//3，引入uniapp工具
	import {
		chooseIamge,
		chooseImageFromCamera
	} from '@/api/uniapp/uni.js'

	//4，引入文件网络请求
	import {
		uploadFile
	} from '@/api/http/common.js'

	//5，语音发送参数
	var recordManager = null;
	var recordTimeInterval = null;

	//6，引入网络请求
	import {
		queryGroupByHeadInfo,
		queryGroupUsers
	} from '@/api/http/msg/group.js'
	import {
		queryUserIsRob,
		rob
	} from '@/api/http/msg/redpkg.js'

	//7，引入vuex
	import {
		mapState,
		mapMutations,
		mapActions,
		mapGetters
	} from 'vuex'

	//8，引入实体类对象
	import {
		msgHomeData,
		msgChatData
	} from '@/object/msg.js'

	export default {
		components: {
			chatSendEmoji,
			chatMsgItem,
			chatConTool,
			chatAdd,
			chatVoiceIcon,
			chatAtAnimation,
			chatRedpkgAnimation
		},
		data() {
			return {
				//1，聊天对象
				//1.1，我的信息
				userId: uni.getStorageSync('userId'),
				head: uni.getStorageSync('head'),
				nickname: uni.getStorageSync('nickname'),
				myNickname: uni.getStorageSync('nickname'),
				//1.2，聊天对象信息
				friendName: '', //群聊名称
				msgObjectData: {}, //聊天对象信息
				groupInfo: '', //群聊信息

				isGx: true, //添加好友框
				//isSendMsg: false, //是否能够发送消息
				isShowSend: false,
				//是否能发送消息
				isCanSend: true,
				sendTitle: '群聊禁言', //展示框内容

				//2，聊天内容
				allChatList: [], //所有的聊天信息
				chatList: [], //聊天主要信息
				chatImgs: [], //图片信息
				pageSize: 20,
				pageNum: 1,
				total: 0,

				scrollHeight: 'auto', //消息主要内容高度
				scrollViewId: '', //页面滑动到的高度

				isEdit: true, //展示输入框
				isFocus: false, //输入框获取焦点
				content: '', //输入框内容

				showEmoji: false, //是否展示表情框
				showFile: false, //是否展示工具框
				showVoice: false, //是否展示语音动画

				showPopChatItem: {}, //长按操作的对象
				//长按弹出
				showShade: false,
				showPop: false,
				showHeightStyle: '',
				popButton: [{
					id: 1,
					text: '撤回',
					img: require('@/static/img/msg/tool/01.svg')
				}, {
					id: 2,
					text: '删除',
					img: require('@/static/img/msg/tool/02.svg')
				}],

				//页面宽高信息
				screenHeight: 0,
				windowWidth: 0,
				windowHeight: 0,
				//底部输入框高度
				sendHeight: 50,

				//发送语音参数
				voiceIconTitle: '正在录音...', //语音动画下的文字
				voiceBgColor: '#05C160', //录音动画背景颜色
				voiceTime: 0, //语音计时
				voiceInterval: '', //语音定时器
				recorderManager: uni.getRecorderManager(), //录音参数

				recordTime: 0, //语音时间
				isRecording: false, //开启语音发送
				isShowVoiceIcon: false, //是否按住语音说话按钮

				emojiHight: '200', //表情框可滑动高度
				moreToolHeight: 0, //工具栏高度，

				//at展示框
				isShowAtGroup: false,
				//艾特信息
				atItem: '',
				//群聊成员
				groupUsers: [],

				inputIsEject: false, //弹出框是否弹出

				oldChatListLength: 0, //之前位置
				scrollWithAnimation: false, //是否开启滑动动画
				scrollTop: 0, //滚动条位置

				isShowSendBtn: false,
				isAdjustPosition: false, //页面网上顶

				newMsgVisibility: 'hidden',
				newMsgOpacity: 0,
				// distanceBottom: 0, //距离底部的高度
				// bottomScrollTop: 0, // 距离顶部的高度
				nowScrollTop: 0, //当前距离顶部高度
				messageHeight: 0, //消息列表高度
				nowScrollHeight: 0, //当前可滑动高度

				//红包信息
				showHbMsg: {},
				isShowHb: false,
				openbrnanimation: {}, //红包点击动画
				openrbagmodelshow: false,

				//语音播放
				innerAudioContent: uni.createInnerAudioContext(),
				isChangeBottom: true, // 默认滚动到最底部

				isShowHistoryMsgTips: false

			}
		},
		watch: {
			content() {
				this.isShowSendBtn = this.content.length > 0
			}
		},
		mounted() {
			this.getPageInfo()
		},
		onLoad(e) {
			var msgObject = JSON.parse(e.msgObject)
			//console.log(msgObject)
			this.msgObjectData = msgObject

			this.getChatByPageList(msgObject)

			//消息已读
			this.msgReag(msgObject)

			//获取聊天对象信息
			this.queryGroupByHeadInfo(msgObject.id)

			wx.setNavigationBarTitle({
				title: msgObject.nickname
			})

			//消息监听
			this.listenSocketMsg()
		},
		computed: {
			...mapState('m_chat', ['chatData', 'topMsgData', 'notTopMsgData']),
			...mapGetters('m_chat', ['getChatData']),
		},
		methods: {
			...mapActions('m_chat', ['setMsgList', 'msgReag', 'msgGoTop', 'clearMsgByList', 'addChatData',
				'readRedPkgStore', 'removeMsvById'
			]),
			//1，获取聊天对象信息
			queryGroupByHeadInfo(fid) {
				queryGroupByHeadInfo(parseInt(fid), this.userId).then(res => {
					if (res.data.pubInfo.code !== 0) {
						if (res.data.pubInfo.message == '群聊已解散' || res.data.pubInfo.message == '未建立关系') {
							//开启禁言框
							this.isShowSend = true
							//不能发送
							this.isCanSend = false
							//设置禁言标语
							this.sendTitle = '已退出群聊'
							return;
						}
					}
					//2.3，参数保存
					var busInfo = res.data.busInfo

					this.friendName = busInfo.groupName
					this.groupInfo = busInfo
					//我在群聊中的备注
					if (busInfo.iInGroupRemarks) {
						this.nickname = busInfo.iInGroupRemarks
					}

					wx.setNavigationBarTitle({
						title: busInfo.groupName
					})
					//console.log(busInfo.identity)
					//判断是否禁言
					if (busInfo.estoppel == '1') {
						//判断用户身份
						if (busInfo.identity != '1' && busInfo.identity != '2') {
							//开启禁言框
							this.isShowSend = true
						}
					}
				})
			},

			//2，获取页面高度
			getPageInfo() {
				uni.getSystemInfo({
					success: (res) => {
						this.$nextTick(() => {
							this.screenHeight = res.windowHeight
							this.windowWidth = res.windowWidth
							this.windowHeight = res.windowHeight

							this.setScrollHeight()
						})
					}
				})
			},
			//2.1，设置scroll的高度
			setScrollHeight(chaneBottomHeight = 0, isgotoBottom = false, timegotoBottom = 50, isShowJp = false) {

				// #ifdef MP-WEIXIN
				this.scrollHeight = `calc(100vh - 110rpx - ${chaneBottomHeight}px)`
				// #endif
				// #ifdef APP-PLUS
				let systemInfo = uni.getSystemInfoSync();
				if (systemInfo.platform == 'ios') {
					this.isAdjustPosition = true

					if (isShowJp) {
						this.scrollHeight = `calc(100vh - 110upx)`
					} else {
						this.scrollHeight = `calc(100vh - 110upx - ${chaneBottomHeight}px)`
					}
				} else {
					this.scrollHeight = `calc(100vh - 110upx - ${chaneBottomHeight}px)`
				}

				// #endif
				// #ifdef H5
				this.scrollHeight = `calc(100vh - 110upx - 44px - ${chaneBottomHeight}px)`
				// #endif

				if (isgotoBottom) {
					this.initScrollBar(timegotoBottom)
				}
			},
			//2.2，页面滚动监听
			onScroll(event) {
				var that = this
				that.nowScrollTop = event.detail.scrollTop
				that.nowScrollHeight = event.detail.scrollHeight

				if (event.detail.scrollTop < 10) {
					//上拉加载更多消息
					console.log('上拉加载更多消息')
					setTimeout(() => {
						that.getHistoryMsg()
					}, 30)

					return
				}

				if (event.detail.scrollHeight - event.detail.scrollTop - that.messageHeight < 260) {
					//滚动到低于，150像素，则关闭新消息提示
					setTimeout(() => {
						this.closeNewTips()
					}, 30)
				}

			},
			//2.3，页面滚动到底部监听
			onScrolltolower(e) {
				//console.log('滚动到底部了')
				//滚动到底部的时候，设置距离顶部的高度
				// var that = this
				// setTimeout(() => {
				// 	that.bottomScrollTop = e.scrollTop
				// }, 100)
				//this.closeNewTips()
				//到底部，则改变总长度
				this.$emit('changeMsgListLeng', true)
			},
			//2.4，滚动到指定位置
			initScrollBar(time = 30, isSendMsg = true) {
				if (!isSendMsg) {
					var that = this
					// 获取 消息列表高度
					uni.createSelectorQuery().select('.message').boundingClientRect((res) => {
						that.messageHeight = res.height
						if (that.nowScrollHeight - that.nowScrollTop - res.height > 260) {
							//距离底部超过300 px不用滚动到底部
							console.log('距离底部超过260 px不用滚动到底部')
							that.showNewTips()

							//到底部，则改变总长度
							that.$emit('changeMsgListLeng', false)
							return
						} else {
							//到底部，则改变总长度
							that.$emit('changeMsgListLeng', true)
							that.gotoBottomFunction(time)
						}
					}).exec()
				} else {
					this.gotoBottomFunction(time)
				}

			},
			gotoBottomFunction(time = 50, scrollViewId = 'bottom-anchor') {
				console.log(scrollViewId)
				var that = this
				setTimeout(() => {
					if (that.chatList.length == 0) {
						return
					}
					//console.log('滚动到最底部')
					that.scrollViewId = '';
					that.$nextTick(function() {
						let len = that.chatList.length - 1
						that.scrollViewId = scrollViewId
					})
				}, time)
			},

			//3.1，查询页面聊天消息
			getChatByPageList(msgObjectData) {
				//1，遍历所有的聊天信息
				for (var i = 0; i < this.chatData.length; i++) {
					if (this.chatData[i].id == msgObjectData.id &&
						this.chatData[i].type == msgObjectData.type) {
						//2，获取当前聊天的总聊天信息
						var newChatData = this.chatData[i].list

						if (newChatData.length == 0) {
							console.log('没有消息')
							return
						}
						//console.log(newChatData)
						this.allChatList = newChatData

						this.getHistoryMsg(true, 0)

						/* //3，查询第一页的数据
						var onePageData = newChatData.slice(this.pageNum, this.pageNum + this.pageSize)
						for (var j = 0; j < onePageData.length; j++) {
							//3，判断消息类型是否为图片
							if (onePageData[j].msgType == 2) {
								this.chatImgs.unshift(onePageData[j].news)
							}
						}
						//4，给展示的列表赋值
						this.chatList = onePageData.concat(this.chatList)
			
						// this.chatList.unshift(onePageData)
						break; */
					}
				}

			},
			//3.2，加载历史消息
			getHistoryMsg(isgotoBottom = false, queryTime = 500) {
				//console.log(this.pageNum)
				var that = this
				if (!isgotoBottom) {
					this.isShowHistoryMsgTips = true
				}
				setTimeout(() => {
					//1，计算从第几条开始
					var startIndex = (that.pageNum - 1) * that.pageSize
					var endIndex = that.pageNum * that.pageSize
					//2，获取新的历史消息
					var newHistoryMsg = that.allChatList.slice(startIndex, endIndex)
					if (newHistoryMsg.length == 0) {
						this.isShowHistoryMsgTips = false
						console.log('没有更多消息')
						return
					}

					// var gotoMsgViewId = ''
					// if (that.chatList.length !== 0) {
					var gotoMsgViewId = newHistoryMsg[0].msgId
					//}
					//逆序
					newHistoryMsg.reverse()
					that.chatList = [...newHistoryMsg, ...that.chatList];
					if (isgotoBottom) {
						that.gotoBottomFunction(0)
					} else {
						//this.goto

						//that.$refs.myChatRef.gotoBottomFunction(0, 'msg' + gotoMsgViewId)
						//this.gotoMsgView('#msg' + gotoMsgViewId)
						that.gotoBottomFunction(0, 'msg' + gotoMsgViewId)
						this.isShowHistoryMsgTips = false
					}

					//加载新的一页
					that.pageNum = that.pageNum + 1
				}, queryTime);
			},
			gotoMsgView(selector) {
				//console.log(selector)
				console.log(uni.createSelectorQuery())
				console.log(uni.createSelectorQuery().in(this))
				let view = uni.createSelectorQuery().in(this).select(selector);
				view.boundingClientRect((res) => {
					this.$refs.scrollViewRef({
						scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度，示意上面还有信息。
						duration: 0
					});
				}).exec();

				// var that = this
				// setTimeout(() => {
				// 	uni.createSelectorQuery().select(selector).boundingClientRect(data => {
				// 		console.log(data)
				// 		const targetTop = data.top; // 获取距离顶部的距离
				// 		const scrollDistance = targetTop + 300; // 距离减去30px后的位置
				// 		that.scrollViewToId(scrollDistance); // 调用滚动方法
				// 	}).exec();
				// }, 5000);
			},
			scrollViewToId(distance) {
				console.log(distance)
				this.scrollTop = distance
				this.$refs.scrollViewRef.scrollTo({
					scrollTop: distance,
					duration: 50, // 滚动动画时长
					easingFunc: "easeIn" // 滚动动画缓动函数
				});
			},

			//4，时间显示工具
			computeDate(createTime, index) {
				if (createTime) {
					if (uni.getSystemInfoSync().platform === 'android') {
						//console.log('运行Android上')
						var datetime = new Date(createTime)
						let date = new Date()

						if (index > 0) {
							//获取上一个
							let beforetime = this.chatList[index - 1].time
							let beforetimestrap = new Date(beforetime)
							if ((datetime - beforetimestrap) > 180000) {
								return this.getTime(createTime)
							} else {
								return ''
							}
						} else {
							return this.getTime(createTime)
						}

					} else {
						//console.log('运行iOS上')
						var datetime = new Date(createTime.replace(/-/g, '/'))
						let date = new Date()

						if (index > 0) {
							//获取上一个
							let beforetime = this.chatList[index - 1].time
							let beforetimestrap = new Date(beforetime.replace(/-/g, '/'))
							if ((datetime - beforetimestrap) > 180000) {
								return this.getTime(createTime.replace(/-/g, '/'))
							} else {
								return ''
							}
						} else {
							return this.getTime(createTime.replace(/-/g, '/'))
						}
					}
				} else {
					return ''
				}
			},
			//4.1，获取时间
			getTime(time) {
				if (uni.getSystemInfoSync().platform === 'android') {
					//console.log('运行Android上')
					return handleTime(time)
				} else {
					//console.log('运行iOS上')
					return handleTime(time.replace(/-/g, '/'))
				}
			},

			//5，消息发送
			//5.1.1，语音输入框切换
			toggleEdit(bool) {
				this.isEdit = bool
				this.isFocus = bool
				this.setScrollHeight(0, true, 20)
			},
			//5.1.2，表情库和工具框展示
			togglePicker(height = 0, type = '') {
				//this.initScrollBar(10)
				this.showEmoji = false
				this.showFile = false
				let status = height > 0 ? true : false
				var that = this

				uni.onKeyboardHeightChange(res => {
					if (res.height > 0) {
						return
					} else {
						switch (type) {
							case 'emoji':
								that.isEdit = true
								//this.isFocus = true
								that.showEmoji = status;
								break
							case 'file':
								that.showFile = status;
								break
						}
						if (that.moreToolHeight > 0 && height > 0) {
							height = that.moreToolHeight
						}
						if (status) {
							that.setScrollHeight(height, true, 150)
						} else {
							that.setScrollHeight(height, false, 150)
						}
						return
					}
				})

				switch (type) {
					case 'emoji':
						that.isEdit = true
						//this.isFocus = true
						that.showEmoji = status;
						break
					case 'file':
						that.showFile = status;
						break
				}
				if (that.moreToolHeight > 0 && height > 0) {
					height = that.moreToolHeight
				}
				if (status) {
					that.setScrollHeight(height, true, 150)
				} else {
					that.setScrollHeight(height, false, 150)
				}

			},

			//5.2，输入框监听
			inputFocus(e) {
				var iosHeight = uni.getSystemInfoSync().safeAreaInsets
				//console.log(iosHeight)
				if (e.detail.height > 0) {
					this.inputIsEject = true
					this.showEmoji = false;
					this.showFile = false;
					// if (this.moreToolHeight == 0) {
					// 	this.moreToolHeight = e.detail.height
					// 	this.emojiHight = parseFloat(e.detail.height) + 20 + ''
					// }
					this.setScrollHeight(e.detail.height, false, 50, true)
				} else {
					this.inputIsEject = false
					this.setScrollHeight(e.detail.height, false, 50)
				}
				//console.log(e.detail.height)
				//this.setScrollHeight(e.detail.height, false, 50)

				uni.onKeyboardHeightChange(res => {
					this.inputIsEject = true
					if (res.height > 0) {
						// if (this.moreToolHeight == 0) {
						// 	this.moreToolHeight = e.detail.height
						// 	this.emojiHight = parseFloat(e.detail.height) + 20 + ''
						// }

						this.showEmoji = false;
						this.showFile = false;
						this.setScrollHeight(e.detail.height, false, 50, true)
					} else {
						this.inputIsEject = false
						this.setScrollHeight(res.height, false, 50)
					}
					//console.log(res.height)
					//this.setScrollHeight(res.height, false, 50)
				})
			},
			//5.3
			submitInput(e) {
				console.log(123123)
				console.log(e)
			},

			//6，点击表情，在输入框中显示
			clickEmoji(e) {
				this.content += e
			},
			//7，文本消息发送
			sendMessage(e) {
				if (e.detail.value == '' || e.detail.value == null) {
					return
				}

				if (this.atItem == '') {
					this.sendMsgByUser(e.detail.value, 1)
					//console.log(e)
				} else {

					if (e.detail.value.indexOf('@' + JSON.parse(this.atItem).nickname) !== -1) {
						var atMsg = JSON.parse(this.atItem)
						atMsg.atMsgNew = e.detail.value.substring(JSON.parse(this.atItem).nickname.length + 1, e.detail
							.value.length)
						//console.log(atMsg)
						this.sendMsgByUser(JSON.stringify(atMsg), 31)
						this.atItem = ''
					} else {
						this.atItem = ''
						this.sendMsgByUser(e.detail.value, 1)
					}

				}
				setTimeout(() => {
					//清空聊天框
					this.content = ''
				}, 10)
			},
			//8，按钮
			sendMessageByBtn() {
				if (this.content == '' || this.content == null) {
					return
				}
				this.sendMsgByUser(this.content, 1)
				//清空聊天框
				this.content = ''
			},
			//8.2，关闭@弹框
			closeAtGroup() {
				this.isShowAtGroup = false
			},
			//8.3，点击@成员
			selectUser(e) {
				//console.log(e)
				this.atItem = JSON.stringify(e)
				//console.log(atItem)
				this.isShowAtGroup = false
				this.content = this.content.substring(0, this.content.length - 1)
				//console.log(this.content)
				this.content += '@' + e.nickname
			},
			//9，文本输入监听
			textareaBInput(e) {
				if (this.msgObjectData.type == 2) {
					return
				}
				var inputText = e.detail.value
				//console.log(inputText)
				if (inputText == '@') {
					//console.log('添加@成员')
					queryGroupUsers(this.msgObjectData.id, '', '', '1').then(res => {
						if (res.data.pubInfo.code !== 0) {
							return uni.$showMsg(res.data.pubInfo.message);
						}
						this.groupUsers = res.data.busInfo

						//隐藏键盘
						uni.hideKeyboard()
						this.isShowAtGroup = true
					})

				}
			},

			//9.1，发送图片
			chooseIamgeFromAlbum() {
				var that = this
				chooseIamge('album').then(res => {
					const filePaths = res.tempFilePaths
					for (let i = 0; i < filePaths.length; i++) {
						//图片上传
						uploadFile(filePaths[i]).then(result => {
							if (result.data.pubInfo.code !== 0) {
								return uni.$showMsg(result.data.pubInfo.message);
							}
							//var  = result.data.busInfo
							that.sendMsgByUser(result.data.busInfo, 2)
						})

						//this.send(filePaths[i], 1)
					}
				})
			},
			//9.2，照相发送
			chooseIamgeFromCamera() {
				var that = this
				chooseImageFromCamera().then(res => {
					uploadFile(res).then(result => {
						if (result.data.pubInfo.code !== 0) {
							return uni.$showMsg(result.data.pubInfo.message);
						}
						//var  = result.data.busInfo
						that.sendMsgByUser(result.data.busInfo, 2)
					})
				})
			},
			//9.3，图片加载成功
			imgLoad() {},
			//9.4，查看图片
			showImg(e) {
				var that = this
				uni.previewImage({
					current: e.news,
					urls: this.chatImgs,
					longPressActions: {
						itemList: ['保存图片'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');

							uni.downloadFile({
								url: that.chatImgs[data.index],
								success: (res) => {
									if (res.statusCode === 200) {
										uni.saveImageToPhotosAlbum({
											filePath: res.tempFilePath,
											success: function() {
												//uniapp提供的消息提示框。
												uni.showToast({
													title: "保存成功",
													icon: "success"
												});
											},
											fail: function() {
												uni.showToast({
													title: "保存失败，请稍后重试",
													icon: "none"
												});
											}
										});
									}
								}
							})

						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				})
			},

			//10，点击好友头像设置
			gotoUserSet(item) {
				if (this.groupInfo.protect == '1' && this.groupInfo.identity == '3') {
					//开启保护模式
					console.log('目前为群保护模式！')
					return;
				}

				if (item.sendId == this.userId) {
					//用户点击自己的头像
					return;
				}

				var req = {
					id: item.sendId,
					nickname: item.sendNickname,
					head: item.sendHead,
					type: 2, //用户群聊
				}

				uni.navigateTo({
					url: '/subpkg/msg/user/user-describe/user-describe?msgObject=' + JSON.stringify(req),
				})
			},

			//11，发送红包
			sendRedPkg() {
				if (!uni.getStorageSync('identifyCheck')) {
					return uni.$showMsg('请先进行实名认证！')
				}

				uni.navigateTo({
					url: '/subpkg/msg/red-pkg/red-pkg-send/red-pkg-send?msgObject=' + JSON.stringify(this
						.msgObjectData)
				})
			},
			//11，打开红包
			//11.1，点击红包消息
			showRedPkg(item) {
				//判断是否实名认证 如果没有实名认证无法下单
				if (!uni.getStorageSync('identifyCheck')) {
					return uni.$showMsg('请先进行实名认证！')
				}
				//console.log(item)
				//this.isShowHb = true
				this.showHbMsg = item
				if (!item.isRedRead) {
					var req = item
					req.type = 3
					req.id = this.msgObjectData.id
					//红包已读
					this.readRedPkgStore(req)
				}

				//console.log(item)
				//如果是专属红包无法零钱
				var newMsg = JSON.parse(item.news)
				if (newMsg.hbType == '3') {
					if (item.sendId == this.userId) {
						//跳转到详情页面
						var redPkgMsgInfo = {
							redPkgId: item.redPkgId,
							identity: this.groupInfo.identity,
							protect: this.groupInfo.protect
						}
						return uni.navigateTo({
							url: '/subpkg/msg/red-pkg/red-pkg-group/red-pkg-group?redPkgMsgInfo=' +
								JSON
								.stringify(redPkgMsgInfo)
						});
					} else {
						if (newMsg.appointUserId != this.userId) {
							//不是指定对象，无法领取
							return uni.$showMsg('您无权领取！');
						}
					}
				}
				queryUserIsRob(item.redPkgId).then(res => {
					if (res.data.pubInfo.code !== 0) {
						//该用户已经抢过红包或是红包已经抢完
						//return uni.$showMsg(res.data.pubInfo.message);

						var redPkgMsgInfo = {
							redPkgId: item.redPkgId,
							identity: this.groupInfo.identity,
							protect: this.groupInfo.protect
						}

						return uni.navigateTo({
							url: '/subpkg/msg/red-pkg/red-pkg-group/red-pkg-group?redPkgMsgInfo=' +
								JSON
								.stringify(redPkgMsgInfo)
						})
					}
					//还有剩余红包，可以抢
					this.isShowHb = true
				})
			},
			//11.2，关闭红包
			closeHbFun() {
				this.isShowHb = false
			},
			//11.3，开始抢红包
			openHbFun(item) {
				var that = this;
				var animation = uni.createAnimation({
					duration: 1000,
					timingFunction: 'ease',
				})
				that.openbrnanimation = animation;
				// animation.rotate3d(0,1,0,360).step();
				animation.rotateY(360).step();
				that.openbrnanimation = animation.export();

				//console.log(item)
				rob(item.redPkgId, this.userId, this.nickname).then(res => {
					if (res.data.pubInfo.code !== 0) {
						//该用户已经抢过红包或是红包已经抢完
						uni.$showMsg(res.data.pubInfo.message);
					} else {
						//抢到了红包，发送消息
						//sendId, sendName, redPkgId, robId, robName
						//console.log(JSON.parse(item.news).hbType)

						var robHbMsgInfo = {
							sendId: item.sendId,
							sendName: item.sendNickname,
							redPkgId: item.redPkgId,
							robId: that.userId,
							robName: that.myNickname,
							robAmount: res.data.busInfo.robAmount,
							title: res.data.busInfo.title,
							surplusAmount: res.data.busInfo.surplusAmount,
							totalAmount: res.data.busInfo.totalAmount,
							totalNum: res.data.busInfo.totalNum,
							generateArr: res.data.busInfo.generateArr,
							readUserIds: res.data.busInfo.readUserIds,
							maxIndex: res.data.busInfo.maxIndex,
							maxAmount: res.data.busInfo.maxAmount,
							type: res.data.busInfo.type,
							readUserNames: res.data.busInfo.readUserNames,
							hbType: JSON.parse(item.news).hbType
						}
						//robHbMsg()
						var sendData = {
							types: 21, //消息类型 （0文本，1图片连接，2音频，3地图）
							msg: JSON.stringify(robHbMsgInfo)
						}
						that.socketSendMsg(sendData)
					}

					//console.log(res.data.busInfo)
					that.isShowHb = false
					//that.rbagmodelshow = false;
					that.openrbagmodelshow = true;
					that.openbrnanimation = {};

					var redPkgMsgInfo = {
						redPkgId: item.redPkgId,
						identity: this.groupInfo.identity,
						protect: this.groupInfo.protect
					}

					return uni.navigateTo({
						url: '/subpkg/msg/red-pkg/red-pkg-group/red-pkg-group?redPkgMsgInfo=' + JSON
							.stringify(redPkgMsgInfo)
					})
				})
			},
			//11.4，查看红包
			gotoDetail(item) {
				var redPkgMsgInfo = {
					redPkgId: item.redPkgId,
					identity: this.groupInfo.identity,
					protect: this.groupInfo.protect
				}

				return uni.navigateTo({
					url: '/subpkg/msg/red-pkg/red-pkg-group/red-pkg-group?redPkgMsgInfo=' + JSON
						.stringify(redPkgMsgInfo)
				})
			},


			//12，长按弹框
			longpressItem(item, chatItem) {
				//console.log(chatItem)
				if (chatItem.isWithdraw && chatItem.sendId == this.userId) {
					//可以撤回
					this.popButton = [{
						id: 1,
						text: '撤回',
						img: require('@/static/img/msg/tool/01.svg')
					}, {
						id: 2,
						text: '删除',
						img: require('@/static/img/msg/tool/02.svg')
					}]
				} else {
					//无法撤回
					this.popButton = [{
						id: 2,
						text: '删除',
						img: require('@/static/img/msg/tool/02.svg')
					}]
				}


				this.showPopChatItem = chatItem
				//计算光标高度（距离顶部导航栏的距离）
				var height = parseInt(item.pageY)
				var width = parseInt(item.pageX)
				var bottomHeight = (this.windowHeight - this.sendHeight - 50)
				var leftWidth = this.windowWidth * 0.7
				var rightWidth = this.windowWidth * 0.22
				//this.windowWidth - width

				if (height < 45) {
					//1，如果小于弹框高度则固定位置
					if (width > leftWidth) {
						this.showHeightStyle = `top:60px;right:${rightWidth}px;`
					} else {
						this.showHeightStyle = `top:60px;left:${width}px;`
					}
				} else if (bottomHeight < height) {
					//2，如果，在底部的话则固定在上面
					if (width > leftWidth) {
						this.showHeightStyle = `bottom:${this.sendHeight + 30}px;right:${rightWidth}px;`
					} else {
						this.showHeightStyle = `bottom:${this.sendHeight + 30}px;left:${width}px;`
					}
				} else {
					if (width > leftWidth) {
						this.showHeightStyle = `top:${height}px;right:${rightWidth}px;`
					} else {
						this.showHeightStyle = `top:${height}px;left:${width}px;`
					}
				}

				this.showShade = true;
				this.$nextTick(() => {
					setTimeout(() => {
						this.showPop = true;
					}, 10);
				});
			},
			//12.1，关闭弹框
			closeShowTool() {
				this.showPop = false;
				//this.pickerUserIndex = -1;
				setTimeout(() => {
					this.showShade = false;
				}, 10);
			},
			//12.2选择其中的一个
			pickerMenu(item) {
				//console.log(this.showPopChatItem)
				if (item.id == 2) {
					this.closeUserMsg(this.showPopChatItem)
					//this.$emit('closeUserMsg', this.showPopChatItem)
				} else {
					this.withdrawUserMsg(this.showPopChatItem)
					//this.$emit('withdrawUserMsg', this.showPopChatItem)
				}
			},
			//13，删除消息
			closeUserMsg(showPopChatItem) {
				//删除消息
				for (var i = 0; i < this.chatList.length; i++) {
					if (this.chatList[i].msgId == showPopChatItem.msgId) {
						this.chatList.splice(i, 1)
						continue;
					}
				}
				this.removeMsvById(showPopChatItem)
				return
			},
			//14，撤回消息
			withdrawUserMsg(showPopChatItem) {
				let data = {
					msg: '撤回一条消息',
					types: 11
				}
				this.socketSendMsg(data, showPopChatItem.msgId)
			},

			//15，启动语音发送
			startVoice() {
				this.$nextTick(() => {
					recordManager = uni.getRecorderManager()
					recordManager.onStart(() => {
						console.log('开启动画')
						//展示语音动画
						this.isShowVoiceIcon = true

						recordTimeInterval = setInterval(() => {
							this.recordTime += 1;
							//this.formatedRecordTime = util.formatTime(this.recordTime)

							if (this.recordTime > 10) {
								//结束计时
								clearInterval(recordTimeInterval)
								this.micTouchEnd()
							}
						}, 1000)
					})
					recordManager.onStop((res) => {
						if (this.isCancel) {
							//this.formatedRecordTime = "00:00:00"
							this.isCancel = false
							this.recordTime = 0
						} else {
							if (this.recordTime < 1) {
								this.recordTime = 0
								//console.log('时间太短')
								uni.showToast({
									icon: 'none',
									title: '发送时间太短',
									duration: 1000
								})
								return
							} else {

								uploadFile(res.tempFilePath).then(result => {
									if (result.data.pubInfo.code !== 0) {
										this.isShowClose = false
										this.isShowVoiceIcon = false;
										//归为时长
										this.recordTime = 0
										return uni.$showMsg(result.data.pubInfo.message);
									}
									//var  = result.data.busInfo
									let data = {
										voice: result.data.busInfo,
										time: this.recordTime,
										//标识是否执行
										anmitionPlay: false
									}
									//console.log(result.data.busInfo)
									this.sendMsgByUser(JSON.stringify(data), 3)
									//this.$emit('sendMsgByUser', JSON.stringify(data), 3)
									this.recordTime = 0
								})
							}
						}
					})
				})
			},
			//15.1，按住说话
			micTouchStart(e) {
				// #ifdef APP-PLUS
				plus.device.vibrate(50); //震动
				// #endif

				this.isRecording = true
				recordManager.start({
					format: 'mp3'
				})
			},
			micTouchMove(e) {
				//距离顶部位置
				const pointY = e.touches[0].clientY
				//console.log(this.windowHeight)
				if ((this.windowHeight - 100) > pointY) {
					this.voiceIconTitle = '松开取消发送'
					//console.log('松开')
					this.voiceBgColor = '#FA5251'


					this.isShowClose = true
					this.isCancel = true
				} else {
					this.voiceIconTitle = '正在录音... '
					this.voiceBgColor = '#05C160'

					this.isShowClose = false
					this.isCancel = false
				}
			},
			micTouchCancel(e) {
				this.isRecording = false
				clearInterval(recordTimeInterval)
				recordManager.stop()
				this.isShowVoiceIcon = false;
				this.isShowClose = false

				//this.voiceTime = 0;
				this.voiceIconTitle = '按住 说话';
				this.voiceBgColor = '#05C160'
			},
			micTouchEnd(e) {
				this.isRecording = false
				clearInterval(recordTimeInterval)
				recordManager.stop()
				this.isShowVoiceIcon = false;
				this.isShowClose = false

				//this.voiceTime = 0;
				this.voiceIconTitle = '按住 说话';
				this.voiceBgColor = '#05C160'

			},

			//16，点击语音，播放
			handleAudio(voice) {
				this.$emit("handleAudio", voice)
			},

			//17，有新的消息，展示新的消息提示框
			showNewTips() {
				this.newMsgVisibility = 'visible'
				this.newMsgOpacity = 1
			},
			//17.2，关闭
			closeNewTips() {
				this.newMsgVisibility = 'hidden'
				this.newMsgOpacity = 0
			},
			//17.3，点击新提示，滚动到最底部
			gotoBottomByTips() {
				this.initScrollBar(30)
				this.closeNewTips()
			},

			//消息发送
			sendMsgByUser(msg, types) {
				var data = {
					types,
					msg
				}
				this.socketSendMsg(data, 0)
				//this.$emit('sendMsg', data)
			},


			//websocket
			//1，socket发送消息
			socketSendMsg(e, msgId) {
				if (!this.isCanSend) {
					console.log('群聊已解散')
					return
				}
				var that = this
				var nowTime = getNowTime() + ''

				//消息组装
				let msgData = {
					type: this.$chatType.CHAT_GROUP,
					msg: {
						id: msgId || 0,
						groupId: this.msgObjectData.id,
						senderId: this.userId,
						types: e.types, //消息类型 （0文本，1图片连接，2音频，3地图）
						message: e.msg, //消息 
						time: nowTime,
						groupHead: this.msgObjectData.head,
						groupName: this.msgObjectData.nickname,
						senderHead: this.head,
						senderName: this.myNickname,
						state: 0
					}
				}

				//console.log(msgData)
				var that = this
				uni.myWebsocket.socketTask.send({
					data: JSON.stringify(msgData),
					async success() {},
					fail(e) {
						uni.$showMsg('发送失败！');
						uni.myWebsocket.socketTask.close
						uni.myWebsocket = ''
						that.connectSocketInit()
					}
				});
			},
			//2，消息监听
			listenSocketMsg() {
				if (uni.myWebsocket == undefined || uni.myWebsocket == '' || uni.myWebsocket == null) {
					//连接上websocket
					uni.$connectSocketInit.connectSocket(uni.$nettyPort)
				}

				//消息监听
				var that = this
				uni.myWebsocket.socketTask.onMessage((result) => {
					var res = JSON.parse(result.data)

					if (res.type == uni.$chatType.CHAT_GROUP && res.params.groupId == that.msgObjectData.id) {
						//群聊禁言
						if (res.params.types == uni.$chatType.ESTOPPEL) {
							//console.log(res.params.message)
							//res.params.message.indexOf('开启') != -1 
							if (that.isContainStr(res.params.message, '开启')) {
								//判断用户身份
								if (that.groupInfo.identity != '1' && that.groupInfo.identity != '2') {
									//开启禁言框
									that.isShowSend = true
								}
							} else {
								that.isShowSend = false
							}

							//console.log(res.params.message)
							//that.queryGroupByHeadInfo(res.params.groupId, that.userId)
						} else if (res.params.types == uni.$chatType.PROTECT) {
							//console.log(res.params.message)
							// res.params.message.indexOf('开启') != -1 /
							if (that.isContainStr(res.params.message, '开启')) {
								//判断用户身份
								//console.log('测试1')
								that.groupInfo.protect = '1';
							} else {
								//console.log('测试2')
								that.groupInfo.protect = '2';
							}
						} else if (res.params.types == uni.$chatType.KICK_OUT_USER) {
							//踢出群聊
							var userId = JSON.parse(res.params.message).userId
							if (that.userId == userId) {
								//开启禁言框
								that.isShowSend = true
								//不能发送
								that.isCanSend = false
								//设置禁言标语
								that.sendTitle = '已退出群聊'
							}

						}
					} else if (res.type == uni.$chatType.DISSOLUTION_GROUP) {
						//群聊解散
						that.isCanSend = false
					}

				})

			},

			isContainStr(str1, str2) {
				if (str1 == null || str2 == null) {
					return false
				}
				return (str1.indexOf(str2) !== -1)
			}

		}
	}
</script>

<style lang="scss">
	// 引入公共样式
	@import "../common/css/global.scss";
</style>